const fs = require('fs')
const path = require('path')
const Glob = require('glob')
const pify = require('pify')
const log = require('../utils/log')
const file = require('../utils/file')
const resolve = file => path.resolve(__dirname, file)
const glob = pify(Glob)

const templet_file = resolve('../templets/page.templet.vue')
const routes_dir = resolve('../../.kyeteo/router')
const routes_file = routes_dir + '/routes.js'


const getRoutes = async () => {
    let files = {}, routes = [], all = []
    all = await glob(`pages/**/*.{vue,js}`, {
        cwd: path.resolve(process.cwd(), './src'),
        ignore: ['**/*.test.*', '**/*.spec.*', '**/-*.*']
    })
    all.forEach((f) => {
        const key = f.replace(/\.(js|vue)$/, '')
        if (/\.vue$/.test(f) || !files[key]) {
            files[key] = f.replace(/('|")/g, '\\$1')
        }
    })
    for (let i in files) {
        const rawPath = files[i].match(/pages\/(\S+).vue/)[1]
        const name = rawPath.replace('_id', 'id').split('/').map((j, k) => {
            if (!k) {
                return j
            }
            return j.replace(/^[a-z]/, j.match(/^[a-z]/)[0].toUpperCase())
        }).join('')
        routes.push({
            name,
            path: `/${rawPath.replace(/_id/, ':id')}`,
            component: `resolve => require(['@/pages/${rawPath}'], resolve)`
        })
    }
    return routes
}

const creatRoutesFile = async () => {
    const routes = await getRoutes()
    let string = `/* eslint-disable */\n`
    string += `export const routes = ${JSON.stringify(routes, null, 2)}`
        .replace(/"component": "(.*)"/g, `"component": $1`)
        .replace(/"(.*)":/g, '$1:')
    file.mkdir(routes_dir).then(dir => {
        fs.writeFile(routes_file, string, e => {
            log('green', '文件更新成功')
        })
    })
}

module.exports = name => {
    fs.readFile(templet_file, 'utf-8', function (err, raw) {
        if (err) {
            throw err
        }
        const data = raw.replace(/\$\{name\}/g, name)
        fs.writeFile(resolve('../../src/pages/' + name + '.vue'), data, function (err) {
            if (err) {
                throw err
            }
            creatRoutesFile()
        })
    })
}